<?php

namespace App\Library\Wechat;

use Alipay\EasySDK\Kernel\Factory;
use App\Exceptions\Api\PayException;
use EasyWeChat\Pay\Application as payApp;

class PayWeChatApi
{
    const API_JSAPI_URL = 'v3/pay/transactions/jsapi';

    /**
     * 创建订单返回支付参数
     * @param $pay_params
     * @return array|mixed[]
     */
    public static function payPostJson($pay_params)
    {
        $wechat_config = getWxConfig('MiniApp');
        $pay_params['appid'] =  $wechat_config['app_id'];
        $pay_params['mchid'] =  $wechat_config['mch_id'];
        // 创建微信支付对象
        $wechat = new payApp($wechat_config);
        // 第一步：JSAPI 下单，组装请求参数

        $response = $wechat->getClient()->postJson("v3/pay/transactions/jsapi",$pay_params);
        $result = $response->toArray(false);
        // 请求失败
        if (!isset($result['prepay_id'])) {
            return ['code' => 0, 'data' => '', 'msg' => $result['message']];
        }
        // 第二步：组装小程序调起支付 API
        $prepayId = $result['prepay_id'];
        $appId = $wechat_config['app_id'];
        // 默认RSA，v2要传MD5
        $config = $wechat->getUtils()->buildMiniAppConfig($prepayId, $appId,  'RSA');
        return $config;
    }

    /**
     * 查询 订单 单条数据
     * @param $out_trade_no
     * @return array
     *
     */
    public static function WXPayNotify($out_trade_no)
    {
        try {
            $getConfig = getWxConfig('MiniApp');
            $params = [
                'query' => [
                    // 微信订单号或者商户订单号
                    'mchid' => $getConfig['mch_id']
                ]
            ];
            $wechat = new payApp($getConfig);
            $response = $wechat->getClient()->get("v3/pay/transactions/out-trade-no/{$out_trade_no}", $params);
            $result = $response->toArray();
            if ($result) {
                return ['http_code'=>0,'code'=>0,'data'=>$result];
            } else {
                return ['http_code'=>100,'code'=>0,'msg'=>'失败'];
            }
        } catch (\Exception $e) {
            return ['http_code'=>100,'code'=>0,'msg'=>'失败'];
//            throw new PayException('失败原因:'.$e->getMessage());
        }
    }
    /**
     *
     * 微信 退款
     * @param $param
     */
    public static function pay_refunds($param)
    {
        $out_trade_no=$param['order_sn'];
        $refund_amount=number_format($param['refund_amount']*100,0);
        $total=number_format($param['total']*100,0);
        $out_refund_no=$param['out_refund_no'].rand_str(10,0);
        $refunds_params=[
            // 'transaction_id'=>$out_trade_no,
            'out_trade_no'=>$out_trade_no,
            'out_refund_no'=>$out_refund_no,
            "amount"=>[
                "refund"=> intval($refund_amount),
                'total'=>intval($total),// 订单总金额，单位为分，只能为整数
                "currency" => "CNY"
            ]
        ];
        try {
            $wechat_config = getWxConfig('MiniApp');
            // 创建微信支付对象
            $wechat = new payApp($wechat_config);
            $refunds_response = $wechat->getClient()->postJson("/v3/refund/domestic/refunds",$refunds_params);
            $refunds_result = $refunds_response->toArray(false);
            return   $refunds_result;
        } catch (\Exception $e) {
            throw new PayException($e->getMessage());
        }
    }
    /**
     * 创建订单返回支付参数
     * @param string $orderId
     * @param string $totalFee
     * @param string $attach
     * @param string $body
     * @param string $detail
     * @param array $options
     * @return array|false|mixed|string
     * @author 等风来
     * @email 136327134@qq.com
     * @date 2022/9/22
     */
    public static function create(string $orderId, string $totalFee, string $attach, string $body, string $detail, array $options = [])
    {
        $wechat_config = getWxConfig('MiniApp');
        $pay_params['appid'] =  $wechat_config['app_id'];
        $pay_params['mchid'] =  $wechat_config['mch_id'];
        // 创建微信支付对象
        $wechat = new payApp($wechat_config);
        // 第一步：JSAPI 下单，组装请求参数

        $response = $wechat->getClient()->postJson(self::API_JSAPI_URL,$pay_params);
        $result = $response->toArray(false);
        // 请求失败
        if (!isset($result['prepay_id'])) {
            return ['code' => 0, 'data' => '', 'msg' => $result['message']];
        }
        // 第二步：组装小程序调起支付 API
        $prepayId = $result['prepay_id'];
        $appId = $wechat_config['app_id'];
        // 默认RSA，v2要传MD5
        $config = $wechat->getUtils()->buildMiniAppConfig($prepayId, $appId,  'RSA');
        return $config;


    }
}
